<template>
  <div class="order-history">
    <!-- 页面标题和统计 -->
    <div class="page-header">
      <div class="header-content">
        <h2>订单历史</h2>
        <p>查看您的历史订单记录和回收统计</p>
      </div>
      <div class="stats-summary">
        <div class="stat-item">
          <span class="stat-value">{{ totalOrders }}</span>
          <span class="stat-label">总订单</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">¥{{ totalEarnings }}</span>
          <span class="stat-label">总收益</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">{{ totalWeight }}kg</span>
          <span class="stat-label">总重量</span>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card" shadow="never">
      <div class="filters">
        <div class="filter-group">
          <label>时间范围：</label>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateRangeChange"
          />
        </div>

        <div class="filter-group">
          <label>订单状态：</label>
          <el-select
            v-model="statusFilter"
            placeholder="选择状态"
            clearable
            style="width: 150px"
            @change="handleStatusChange"
          >
            <el-option label="全部状态" value="" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>

        <div class="filter-group">
          <label>回收站点：</label>
          <el-select
            v-model="stationFilter"
            placeholder="选择站点"
            clearable
            style="width: 200px"
            @change="handleStationChange"
          >
            <el-option label="全部站点" :value="null" />
            <el-option
              v-for="station in stations"
              :key="station.id"
              :label="station.name"
              :value="station.id"
            />
          </el-select>
        </div>

        <div class="filter-group">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单号..."
            style="width: 200px;"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-button type="primary" @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置筛选
        </el-button>

        <el-button type="success" @click="exportOrders">
          <el-icon><Download /></el-icon>
          导出记录
        </el-button>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="orders-card" shadow="never">
      <div class="orders-header">
        <span>历史订单 ({{ filteredOrders.length }})</span>
      </div>

      <!-- 订单表格 -->
      <div class="table-responsive">
        <el-table
          :data="paginatedOrders"
          style="width: 100%"
          @row-click="viewOrderDetail"
          stripe
        >
          <el-table-column prop="orderNo" label="订单号" min-width="160">
            <template #default="scope">
              <el-button type="primary" link @click="viewOrderDetail(scope.row)">
                {{ scope.row.orderNo }}
              </el-button>
            </template>
          </el-table-column>
          
          <el-table-column prop="stationName" label="回收站点" min-width="120" />
          
          <el-table-column prop="createTime" label="创建时间" min-width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="completedTime" label="完成时间" min-width="160">
            <template #default="scope">
              {{ scope.row.completedTime ? formatDateTime(scope.row.completedTime) : '-' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="totalAmount" label="订单金额" min-width="110" align="right">
            <template #default="scope">
              <span class="amount">¥{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="totalWeight" label="总重量" min-width="100" align="right">
            <template #default="scope">
              <span>{{ scope.row.totalWeight }}kg</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" min-width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" min-width="120" align="center" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.stop="viewOrderDetail(scope.row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <el-empty 
        v-if="filteredOrders.length === 0" 
        description="暂无历史订单"
        :image-size="200"
      />
    </el-card>

    <!-- 分页 -->
    <div class="pagination-section" v-if="filteredOrders.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredOrders.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      :title="`订单详情 - ${selectedOrder?.orderNo}`"
      width="800px"
      @close="orderDetailVisible = false"
    >
      <div v-if="selectedOrder" class="order-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(selectedOrder.status)">
                {{ getStatusText(selectedOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="回收站点">{{ selectedOrder.stationName }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(selectedOrder.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">
              {{ selectedOrder.completedTime ? formatDateTime(selectedOrder.completedTime) : '未完成' }}
            </el-descriptions-item>
            <el-descriptions-item label="取货地址">{{ selectedOrder.pickupAddress }}</el-descriptions-item>
            <el-descriptions-item label="订单金额">
              <span class="amount">¥{{ selectedOrder.totalAmount }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="总重量">{{ selectedOrder.totalWeight }}kg</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 物品明细 -->
        <div class="detail-section">
          <h3>物品明细</h3>
          <el-table :data="selectedOrder.items" style="width: 100%">
            <el-table-column prop="itemName" label="物品名称" />
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="scope">
                {{ scope.row.quantity }}{{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.unitPrice }}/{{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="小计" width="100">
              <template #default="scope">
                <span class="amount">¥{{ scope.row.subtotal }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 订单时间线 -->
        <div class="detail-section">
          <h3>订单时间线</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(event, index) in selectedOrder.timeline"
              :key="index"
              :timestamp="formatDateTime(event.time)"
              :type="getTimelineType(event.status)"
            >
              <div class="timeline-content">
                <h4>{{ event.title }}</h4>
                <p>{{ event.description }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search,
  Refresh,
  Download
} from '@element-plus/icons-vue'
import { ordersAPI } from '@/api/orders'

// 组件名称
defineOptions({
  name: 'OrderHistory'
})

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('')
const stationFilter = ref(null)
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const orderDetailVisible = ref(false)
const selectedOrder = ref(null)

// 数据
const orders = ref([])
const stations = ref([])

// 统计数据
const totalOrders = ref(0)
const totalEarnings = ref('0.00')
const totalWeight = ref(0)

// 计算属性
const filteredOrders = computed(() => {
  let result = [...orders.value]

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(order =>
      order.orderNo.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(order => order.status === statusFilter.value)
  }

  // 站点筛选
  if (stationFilter.value) {
    result = result.filter(order => order.stationId === stationFilter.value)
  }

  // 时间范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    result = result.filter(order => {
      const orderTime = new Date(order.createTime)
      return orderTime >= new Date(startDate) && orderTime <= new Date(endDate)
    })
  }

  return result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
})

const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 方法
const loadOrders = async () => {
  try {
    loading.value = true
    console.log('📦 加载历史订单...')
    
    // 调用真实的API，只获取已完成和已取消的订单
    const response = await ordersAPI.getMyOrders()
    console.log('📦 API响应:', response)
    
    const allOrders = response.data || response || []
    
    // 只显示已完成和已取消的订单
    const historyOrders = allOrders.filter(order => 
      ['completed', 'cancelled'].includes(order.status)
    )
    
    console.log('📦 历史订单:', historyOrders)
    
    // 映射字段
    orders.value = historyOrders.map(order => ({
      ...order,
      id: order.id,
      orderNo: order.orderNo,
      stationName: order.stationName || '未知站点',
      stationId: order.stationId,
      createTime: order.createdAt,
      completedTime: order.completedAt || order.updatedAt,
      pickupAddress: order.pickupAddress,
      totalAmount: order.totalAmount || 0,
      totalWeight: order.totalWeight || 0,
      status: order.status,
      itemsCount: order.items ? [...new Set(order.items.map(item => item.itemName))].length : 0,
      items: order.items ? order.items.map(item => ({
        itemName: item.itemName || item.item?.name || '未知物品',
        quantity: item.quantity || 0,
        unit: item.unit || 'kg',
        unitPrice: item.unitPrice || 0,
        subtotal: (item.quantity || 0) * (item.unitPrice || 0)
      })) : [],
      timeline: generateTimeline(order)
    }))
    
    console.log('📦 处理后的订单数据:', orders.value)
    
    // 计算统计数据
    calculateStats()
  } catch (error) {
    console.error('加载订单历史失败:', error)
    ElMessage.error('加载订单历史失败')
  } finally {
    loading.value = false
  }
}

// 生成订单时间线
const generateTimeline = (order) => {
  const timeline = []
  
  // 订单创建
  if (order.createdAt) {
    timeline.push({
      time: order.createdAt,
      status: 'pending',
      title: '订单创建',
      description: '您的回收订单已成功创建'
    })
  }
  
  // 订单确认
  if (order.status !== 'cancelled' && order.confirmedAt) {
    timeline.push({
      time: order.confirmedAt,
      status: 'confirmed',
      title: '订单确认',
      description: '回收站已确认您的订单'
    })
  }
  
  // 开始处理
  if (order.status !== 'cancelled' && order.startedAt) {
    timeline.push({
      time: order.startedAt,
      status: 'in_progress',
      title: '开始回收',
      description: '工作人员已到达现场开始回收'
    })
  }
  
  // 订单完成或取消
  if (order.status === 'completed' && order.completedAt) {
    timeline.push({
      time: order.completedAt,
      status: 'completed',
      title: '订单完成',
      description: '回收完成，款项已到账'
    })
  } else if (order.status === 'cancelled' && order.updatedAt) {
    timeline.push({
      time: order.updatedAt,
      status: 'cancelled',
      title: '订单取消',
      description: '订单已取消'
    })
  }
  
  return timeline
}

const loadStations = async () => {
  try {
    // 从订单数据中提取唯一的站点信息
    const uniqueStations = [...new Map(
      orders.value.map(order => [order.stationId, {
        id: order.stationId,
        name: order.stationName
      }])
    ).values()]
    
    stations.value = uniqueStations.filter(s => s.id && s.name)
  } catch (error) {
    console.error('加载站点列表失败:', error)
  }
}

const calculateStats = () => {
  const completedOrders = orders.value.filter(order => order.status === 'completed')
  totalOrders.value = orders.value.length
  totalEarnings.value = completedOrders.reduce((sum, order) => sum + order.totalAmount, 0).toFixed(2)
  totalWeight.value = completedOrders.reduce((sum, order) => sum + order.totalWeight, 0).toFixed(1)
}

const getStatusType = (status) => {
  const types = {
    completed: 'success',
    cancelled: 'danger',
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    completed: '已完成',
    cancelled: '已取消',
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '进行中'
  }
  return texts[status] || '未知'
}

const getTimelineType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString()
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleStatusChange = () => {
  currentPage.value = 1
}

const handleStationChange = () => {
  currentPage.value = 1
}

const handleDateRangeChange = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  stationFilter.value = null
  dateRange.value = []
  currentPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const viewOrderDetail = (order) => {
  selectedOrder.value = order
  orderDetailVisible.value = true
}

const exportOrders = async () => {
  try {
    // 这里应该调用真实的API导出数据
    ElMessage.success('导出功能开发中...')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 生命周期
onMounted(async () => {
  await loadOrders()
  loadStations()
})
</script>

<style scoped>
.order-history {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0;
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-summary {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  min-width: 80px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.filters {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.orders-card {
  border-radius: 8px;
}

.orders-header {
  margin-bottom: 16px;
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

/* 响应式表格容器 */
.table-responsive {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

/* 表格样式优化 */
.table-responsive .amount {
  color: #67C23A;
  font-weight: bold;
  font-size: 14px;
}

/* 移动端表格优化 */
@media (max-width: 768px) {
  .table-responsive :deep(.el-table) {
    font-size: 12px;
  }
  
  .table-responsive :deep(.el-table th),
  .table-responsive :deep(.el-table td) {
    padding: 8px 4px;
  }
  
  .table-responsive :deep(.el-button--small) {
    padding: 4px 8px;
    font-size: 12px;
  }
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 8px;
}

.detail-section .amount {
  color: #67C23A;
  font-weight: bold;
}

.timeline-content h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 14px;
}

.timeline-content p {
  margin: 0;
  color: #666;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .stats-summary {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filter-group {
    width: 100%;
    justify-content: space-between;
  }
  
  .filter-group label {
    min-width: 80px;
  }
  
  .stats-summary {
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex: 1;
    min-width: 70px;
  }
  
  /* 移动端隐藏部分列 */
  .table-responsive :deep(.el-table__cell:nth-child(4)),
  .table-responsive :deep(.el-table__cell:nth-child(6)) {
    display: none;
  }
}

@media (max-width: 576px) {
  .page-header {
    padding: 12px 0;
  }
  
  .header-content h2 {
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .pagination-section :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  /* 超小屏幕进一步简化表格 */
  .table-responsive :deep(.el-table__cell:nth-child(3)) {
    display: none;
  }
}
</style>



